package com.pengtu.gsj.controller.system;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.ibm.icu.util.Calendar;
import com.pengtu.gsj.controller.base.DefaultBaseController;
import com.pengtu.gsj.dao.base.Page;
import com.pengtu.gsj.dao.base.QueryFilter;
import com.pengtu.gsj.dao.base.QueryFilter.MatchType;
import com.pengtu.gsj.entity.app.Attachment;
import com.pengtu.gsj.entity.app.Sysmenu;
import com.pengtu.gsj.entity.app.User;
import com.pengtu.gsj.interceptor.Token;
import com.pengtu.gsj.service.system.SysmenuManagerService;
import com.pengtu.gsj.service.system.SystemManageService;
import com.pengtu.gsj.utils.ConfigUtils;
import com.pengtu.gsj.utils.Constants;
import com.pengtu.gsj.utils.ConverPdfUtils;
import com.pengtu.gsj.utils.DateUtils;
import com.pengtu.gsj.utils.FileUtils;
import com.pengtu.gsj.utils.MathsUtils;
import com.pengtu.gsj.utils.UpDownFileUtils;
import com.pengtu.gsj.utils.UserUtils;
import com.pengtu.gsj.utils.spring.AttachmentUtils;
import com.pengtu.gsj.utils.web.SpringMvcUtils;

@Controller
@RequestMapping("/attachment/")
public class AttachmentController extends DefaultBaseController {
	
	@Autowired
	private SysmenuManagerService sysmenuManagerService;
	
	@Autowired
	private SystemManageService systemManageService;
	
	@RequestMapping("listInfo")
	@Token(save = true)
	public String showAttachmentList(Page<Attachment> page,HttpServletRequest request, Model model) {
		page.setPageSize(Constants.PAGE_SIZE);
		QueryFilter queryFilter = QueryFilter.buildFromHttpRequest(request);
		if (!page.isOrderBySetted()) {
			page.setOrderBy("createDate");
			page.setOrder(Page.DESC);
		}
		String tag = SpringMvcUtils.getParameter("filter_EQS_tag");
		//首先判断文件类型  如果是规章制度和其他类型文件并且是设施局或者管理员  则不需要进行过滤  
		if (!AttachmentUtils.checkFileType(tag)) {
			//如果是辖区局或者是其他单位的用户
			if (UserUtils.getRole().equals("1") || UserUtils.getRole().equals("4")) { 
				//根据当前用户的单位进行过滤
				User user = UserUtils.getUser();
				if (user != null) {
					queryFilter.addFilter("orgId", user.getOrg().getId(), MatchType.EQ);
				}
			}
		}
		page = systemManageService.getAttachmentList(page, queryFilter);
		model.addAttribute("page", page);
		return "system/attachment_list";
	}
	
	/**
	 * 
	 * getAttachmentList:
	 * 适用:动态获取日常巡查的附件信息
	 * @param page  分页信息
	 * @param request
	 * @return 返回某一页的数据
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping(value="list",produces = "application/json; charset=utf-8")
	@ResponseBody
	public Page<Attachment>  getAttachmentList(Page<Attachment> page,HttpServletRequest request) {
		QueryFilter queryFilter = QueryFilter.buildFromHttpRequest(request);
		if (!page.isOrderBySetted()) {
			page.setOrderBy("createDate");
			page.setOrder(Page.DESC);
		}
		page = systemManageService.getAttachmentList(page, queryFilter);
		return page;
	}
	
	/**
	 * 
	 * saveFile:
	 * 适用:保存日常监管模块的文件上传
	 * @param attachment  接受页面传递过来的附件信息
	 * @param request
	 * @param attributes   绑定提示信息
	 * @return  
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping(value = "save", method=RequestMethod.POST)
	@ResponseBody
	public boolean saveFile(@RequestParam(value = "file", required = false) MultipartFile multipartFile, @ModelAttribute Attachment attachment, HttpServletRequest request) throws Exception {
		String tag = SpringMvcUtils.getParameter("tag");
		String data_tag = ((MultipartHttpServletRequest)request).getParameter("data-tag");
		if (StringUtils.isNotEmpty(data_tag)) { //从数据记录中上传文件
			tag = data_tag;
			attachment.setTag(tag);
		}
		Sysmenu sysmenu = sysmenuManagerService.findSysmenuByTag(tag);
		String parentPath = "";
		if (sysmenu != null) {
			attachment.setParentTag(sysmenu.getParent().getTag());
			attachment.setParentTagIds(sysmenu.getParentIds());
			parentPath = sysmenuManagerService.getParentNames(sysmenu)+sysmenu.getName();
			attachment.setKeyWords(com.pengtu.gsj.utils.StringUtils.getKeyWords(parentPath));
		}
		if (StringUtils.isNotEmpty(multipartFile.getOriginalFilename())) { //修改文件时，可以不选择文件，只修改基本信息
			attachment = UpDownFileUtils.getAttachmentByFile(multipartFile,attachment, parentPath);
		}
		systemManageService.saveAttachment(attachment);
		return true;
	}
	
	@RequestMapping(value = "filesUpload", method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> filesUpload(@RequestParam(value = "files[]", required = true) MultipartFile[] multipartFile, HttpServletRequest request) throws IOException {
		String tableId = ((MultipartHttpServletRequest)request).getParameter("tableId");
		String partId = ((MultipartHttpServletRequest)request).getParameter("partId");
		String tableName = ((MultipartHttpServletRequest)request).getParameter("tableName");
		String tableField = ((MultipartHttpServletRequest)request).getParameter("tableField");
		List<Attachment> attList = new ArrayList<Attachment>();
		
		Attachment attachment;
		for(int i = 0; i < multipartFile.length; i++) {
			//写入文件到服务器指定路径
			String path = ConfigUtils.getConfig("lifeProject");
			String fileName = MathsUtils.getRandom()+multipartFile[i].getOriginalFilename();
			File file = new File(path, fileName);
			FileUtils.makeDirectory(file);
			multipartFile[i].transferTo(new File(path, fileName));
			
			//设置附件信息  保存到数据库
			attachment = new Attachment();
			attachment.setTableField(tableField);
			attachment.setTableId(tableId);
			attachment.setPartId(partId);
			attachment.setTableName(tableName);
			attachment.setUploadPerson(UserUtils.getName());
			attachment.setOrgId(UserUtils.getUser().getOrg().getId());
			attachment.setFullPath(fileName);
			attachment.setFileName(FileUtils.getNamePart(multipartFile[i].getOriginalFilename()));
			attachment.setUpfileFileName(FileUtils.getNamePart(multipartFile[i].getOriginalFilename()));
			attachment.setSize(ConverPdfUtils.getSize(multipartFile[i].getSize()));
			attachment.setType( FileUtils.getTypePart(multipartFile[i].getOriginalFilename()));
			attachment.setUpfileContentType(multipartFile[i].getContentType());
			attachment.setFileTime(DateUtils.getCurrentDate());
			if (StringUtils.isEmpty(attachment.getYear())) {
				attachment.setYear(String.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
			}
			attList.add(attachment);
			systemManageService.saveAttachment(attachment);
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("files", attList);
		return map;
	}
	
	/**
	 * 
	 * showAttachment:
	 * 适用:  在修改附件信息的时候
	 * @param attachment  经过前端传过来的id得到的对象
	 * @return  返回附件信息的json数据
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping(value="show")
	@ResponseBody
	public Attachment showAttachment(@ModelAttribute Attachment attachment){
		return attachment;
	}
	
	/**
	 * 
	 * deleteAttachment:
	 * 适用: 删除附件信息的时候
	 * @param attachment  通过前端传过来的id得到的对象
	 * @return  返回成功与否的标识
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping(value="delete")
	@ResponseBody
	public Boolean deleteAttachment(@ModelAttribute Attachment attachment){
		return systemManageService.deleteAttachment(attachment);
	} 
	
	/**
	 * 
	 * showPdf:
	 * 适用:显示pdf文件时，根据swf文件路径，判断文件是否存在
	 * @return
	 * @throws IOException 
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping("showPdf")
	@ResponseBody
	public Boolean showPdf() throws IOException {
		String swfPath = SpringMvcUtils.getParameter("swfPath");
		System.out.println("swfPath:"+swfPath);
		if (StringUtils.isEmpty(swfPath)) {
			return false;
		} 
		String rootPath = ConfigUtils.getConfig("swfFile.path");
		File file = new File(rootPath, swfPath);
		if (file.exists()) {
			return true;
		}
		return false;
	}
	
	/**
	 * 
	 * download:
	 * 适用:附件的下载
	 * @param attachment  根据前端id得到附件对象
	 * @return 二进制流
	 * @throws IOException 
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping("download")
	@ResponseBody
	public ResponseEntity<byte[]> download(@ModelAttribute Attachment attachment) throws IOException {
		String rootPath = ConfigUtils.getConfig("attachment.path");
		if (rootPath.charAt(rootPath.length()-1) != '\\') {
			rootPath += "\\";
		}
		//下载文件路径
		String path = rootPath + attachment.getFullPath();
		return com.pengtu.gsj.utils.FileUtils.downFile(path, attachment.getUpfileFileName());
	}
	
	@RequestMapping("uploads")
	public String showUploads(Model model) {
		String tableId = SpringMvcUtils.getParameter("tableId");
		String partId = SpringMvcUtils.getParameter("partId");
		String tableName = SpringMvcUtils.getParameter("tableName");
		String tableField = SpringMvcUtils.getParameter("tableField");
		
		model.addAttribute("tableId", tableId);
		model.addAttribute("partId", partId);
		model.addAttribute("tableName", tableName);
		model.addAttribute("tableField", tableField);
		return "system/attachment_uploads";	
	}
	
	@RequestMapping("upFiles")
	@ResponseBody
	public Map<String, Object> getUpFiles() {
		String tableId = SpringMvcUtils.getParameter("tableId");
		String partId = SpringMvcUtils.getParameter("partId");
		
		List<Attachment> attList = new ArrayList<Attachment>();
		attList = systemManageService.getAttachmentListByTableId(tableId, partId);
		Map<String,Object> map = new HashMap<String,Object>(10);
		map.put("files", attList);
		return map;
	}
	
	@RequestMapping("fileList")
	public String fileList(Model model){
		String tableId = SpringMvcUtils.getParameter("tableId");
		String partId = SpringMvcUtils.getParameter("partId");
		
		List<Attachment> attList = new ArrayList<Attachment>();
		attList = systemManageService.getAttachmentListByTableId(tableId, partId);
		model.addAttribute("attList", attList);
		model.addAttribute("partId", partId);
		model.addAttribute("size", attList.size());
		return "system/file_list";
	}
	
	
	@RequestMapping("filedown")
	@ResponseBody
	public ResponseEntity<byte[]> filedown(@ModelAttribute Attachment attachment) throws IOException {
		String rootPath = ConfigUtils.getConfig("lifeProject");
		if (rootPath.charAt(rootPath.length()-1) != '\\') {
			rootPath += "\\";
		}
		//下载文件路径
		String path = rootPath + attachment.getFullPath();
		return com.pengtu.gsj.utils.FileUtils.downFile(path, attachment.getUpfileFileName());
	}
	
}
